package userServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swim2.entitybeans.User;
import swim2.sessionbeans.*;

public class NameSearchResultsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public NameSearchResultsServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter out = response.getWriter();
		
		try{
			Context ctx = getInitialContext();			
			UserSystemRemote userSystemRemote = (UserSystemRemote) ctx.lookup("userJNDI");
			String namesearch = request.getParameter("namesearch");
			int userId = Integer.parseInt(request.getParameter("userId"));
			System.out.println("sdsgs"+namesearch+"srgrsg");
			String regex = " ";
			String s[] = namesearch.split(regex);
			ArrayList<User> users = new ArrayList<User>();
			if(!s[0].equals("")){
				users = userSystemRemote.searchUser(s);
			}
			ArrayList<String> usersString = new ArrayList<String>();
			if(users.size() > 0) {	
				for (int i = 0; i < users.size(); i++) {
					usersString.add(users.get(i).getId().toString());
					usersString.add(users.get(i).getName());
					usersString.add(users.get(i).getSurname());
				}
			}
			request.setAttribute("userId", userId);
			request.setAttribute("usersString", usersString);
			RequestDispatcher dispatcher =
			request.getRequestDispatcher("/UserJsp/NameSearchResults.jsp");
			dispatcher.forward(request, response);	
		}
		catch (Exception e) {
			e.printStackTrace();
			out.print("user panel exception");
		}
	}

	static public Context getInitialContext() throws Exception{
		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		env.put(Context.PROVIDER_URL, "localhost:1099");
		return new InitialContext(env);
	}
}
